//
//  HNConsignmentController.m
//  shezhan
//
//  Created by 朱传正 on 2016/10/17.
//  Copyright © 2016年 haoniu. All rights reserved.
//

#import "HNConsignmentController.h"
#import "HNMainController.h"

@interface HNConsignmentController ()<UIWebViewDelegate,UINavigationControllerDelegate,UIActionSheetDelegate,UIImagePickerControllerDelegate>
@property (nonatomic,retain) UIImagePickerController * imagePicker;
@end

@implementation HNConsignmentController

-(void)viewWillAppear:(BOOL)animated{
    [self.navigationController setNavigationBarHidden:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
      [self.navigationController.navigationBar setHidden:YES];
    
    NSString * _loginName = [NSString stringWithFormat:@"%@",[AppConfig getUserInfoByKey:@"hnLoginName"]];
    _webViewUrl = [NSMutableString stringWithFormat:@"%@%@?hnLoginName=%@&&type=%@",url_Base,url_JiMai,_loginName,@"sumai"];
    _webViewUrl = [NSMutableString stringWithFormat:@"%@",[_webViewUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    NSURLRequest * _req = [NSURLRequest requestWithURL:[NSURL URLWithString:_webViewUrl]];
    _webView = [[UIWebView alloc]initWithFrame:CGRectMake(0,0, mainScreenSize.width, mainScreenSize.height)];
    _webView.autoresizingMask = UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleTopMargin|UIViewAutoresizingFlexibleBottomMargin;
    [_webView loadRequest:_req];
    _webView.scrollView.bounces = NO;
    _webView.delegate = self;
    [_webView setBackgroundColor:[AppConfig colorWithHexString:@"#ececec"]];
    [self.view addSubview:_webView];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma -mark WebView
-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
    NSLog(@"WebView erros is %@",error);
    if ([error code] == NSURLErrorCancelled) {
        return;
    }
    // 应用场景:加载从服务器上下载的文件,例如pdf,或者word,图片等等文件
    NSString *filePath = [[NSBundle mainBundle]pathForResource:@"error" ofType:@"html"];
    NSString *htmlString = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
    [webView loadHTMLString:htmlString baseURL:[NSURL URLWithString:filePath]];
}

-(void)webViewDidFinishLoad:(UIWebView *)webView{
    NSLog(@"====webViewDidFinishLoad");
    
    // Disable user selection
    [webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitUserSelect='none';"];
    // Disable callout
    [webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitTouchCallout='none';"];
    
    //JS交互
    JSContext *context=[webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    context[@"JavaScriptInterface"] = self;
}

- (BOOL)webView: (UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    
    return YES;
}

#pragma -mark HNPublishProductJSExport - 设置返回
-(void)HNPublishProductJSExportBack{
    if ([self.webView canGoBack]) {
        [self.webView goBack];
        
    }else{
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            dispatch_async(dispatch_get_main_queue(),^{
                NSLog(@"回归主线程");
                [self.view resignFirstResponder];
                [self.navigationController popViewControllerAnimated:YES];
            });
        });
    }
    NSLog(@"-------goBack---------");

}

-(NSString *)HNPublishProductJSExportReturnLoginName{
    return [[EMClient sharedClient] currentUsername];
}



#pragma mark - HNSettingUserImageJSExport 上传头像
-(void)HNSettingJSExportOutChangeUserImage{
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        
        dispatch_async(dispatch_get_main_queue(),^{
            UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"更换头像" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"从相册选择", @"拍照", nil];
            actionSheet.delegate = self;
            actionSheet.tag = 1001;
            [actionSheet showInView:self.webView];
            self.imagePicker = [[UIImagePickerController alloc]init];
            self.imagePicker.delegate = self;
            self.imagePicker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
            self.imagePicker.allowsEditing = YES;
        });
    });
}

#pragma mark - 判断设备是否有摄像头
- (BOOL) isCameraAvailable
{
    return [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
}
#pragma mark - UIActionSheet delegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (actionSheet.tag==1001) {
        _imagePicker = [[UIImagePickerController alloc] init];
        _imagePicker.editing = YES;
        _imagePicker.allowsEditing = YES;
        _imagePicker.delegate = self;
        if (buttonIndex == 0)
        {
            //相册
            _imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            //[self presentModalViewController:_imagePicker animated:YES];
            [self presentViewController:_imagePicker animated:YES completion:nil];
            
        }else if (buttonIndex == 1){
            //照相机
            if ([self isCameraAvailable]) {
                _imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
                //[self presentModalViewController:_imagePicker animated:YES];
                [self presentViewController:_imagePicker animated:YES completion:nil];
            }else{
                [self showHint:@"该设备没有摄像头"];
            }
        }else
        {
            //取消
        }
    }
    
}
#pragma mark - UIImagePicker delegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    //[picker dismissModalViewControllerAnimated:YES];
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    //UIImage *image = [[info objectForKey:UIImagePickerControllerEditedImage] retain];
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    [self performSelector:@selector(saveImage:) withObject:image afterDelay:0.5];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    //    [[UIApplication sharedApplication]setStatusBarStyle:UIStatusBarStyleLightContent];
    //[picker dismissModalViewControllerAnimated:YES];
    //保持状态栏颜色---为黑色
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
    [picker dismissViewControllerAnimated:YES completion:nil];
}

//上传图片
-(void)saveImage:(UIImage *)image{
    NSLog(@"image = %@",image);
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager manager] initWithBaseURL:[NSURL URLWithString:url_Base]];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    [manager POST:url_UpdateUserImage parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        //压缩图片
        __block UIImage * changeImage = [self compressImage:image toTargetWidth:333];
        
        NSData *data = UIImagePNGRepresentation(changeImage);
        
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        // 设置时间格式
        formatter.dateFormat = @"yyyyMMddHHmmss";
        NSString *str = [formatter stringFromDate:[NSDate date]];
        NSString *fileName = [NSString stringWithFormat:@"%@.png", str];
        [formData appendPartWithFileData:data name:@"file" fileName:fileName mimeType:@"image/png"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        //打印下上传进度
        NSLog(@"上传进度");
        NSLog(@"%@",uploadProgress);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //上传成功
        NSLog(@"上传成功");
        NSError *error;
        NSDictionary * data = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:&error];
        [self hideHud];
        if (error) {
            NSLog(@"====error1:%@",error);
            return;
        }
        NSLog(@"==dict:%@",data);
        NSDictionary *userImageDic = [NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"%@",[data objectForKey:@"imgUrl"]],@"imgUrl", nil];
        
        NSLog(@"userImageDic =  %@",userImageDic);
        
        dispatch_async(dispatch_get_main_queue(), ^{
            NSString *dicStr = [NSString stringWithFormat:@"%@",[AppConfig dictionaryToJson:userImageDic]];
            NSLog(@"dicStr =  %@",dicStr);
            //调用JS 的方法
            NSString *str = [self.webView  stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"upLoadSuccess(%@);",dicStr]];
            
            NSLog(@"str =  %@",str);
        });
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //上传失败
        NSLog(@"上传失败");
        NSLog(@"%@",error.description);
    }];
    
}

//压缩图片
- (UIImage *)compressImage:(UIImage *)sourceImage toTargetWidth:(CGFloat)targetWidth {
    CGSize imageSize = sourceImage.size;
    
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    
    NSLog(@"width = %f,height = %f",width,height);
    
    CGFloat targetHeight = (targetWidth / width) * height;
    NSLog(@"targetWidth = %f targetHeight = %f",targetWidth,targetHeight);
    
    UIGraphicsBeginImageContext(CGSizeMake(targetWidth, targetHeight));
    [sourceImage drawInRect:CGRectMake(0, 0, targetWidth, targetHeight)];
    
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return newImage;
}





@end
